package com.bwie.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.bwie.pojo.Alipay;
import com.bwie.pojo.Order;
import com.bwie.pojo.User;
import com.bwie.service.OrderService;
import com.bwie.service.PayService;
import com.bwie.bean.AliPayBean;
import com.bwie.utils.SnowFlakeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/ali")
public class Order2Controller {

    /**日志对象*/
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private PayService payService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private Alipay alipay;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private OrderService orderService;


    @RequestMapping("/pay")
    @ResponseBody
    public String alipay(String outTradeNo, String subject, String totalAmount, String body) throws AlipayApiException {

        Long snowFlakeId = SnowFlakeUtil.getSnowFlakeId();
        outTradeNo = String.valueOf(snowFlakeId);
        logger.info("商户订单号为{},订单名称为{},付款金额为{},商品描述{}", outTradeNo, subject, totalAmount, body);
        AliPayBean alipayBean = new AliPayBean();
        alipayBean.setOut_trade_no(outTradeNo);
        alipayBean.setSubject(subject);
        alipayBean.setTotal_amount(totalAmount);
        alipayBean.setBody(body);

        return payService.aliPay(alipayBean);
    }

    @RequestMapping("/success")
    @ResponseBody
    public String success() throws UnsupportedEncodingException {
        //验签处理
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, alipay.getPublicKey(),alipay.getCharset(),alipay.getSignType()); //调用SDK验证签名
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if (signVerified){
            String s = redisTemplate.opsForValue().get("user");
            User user = JSONObject.parseObject(s, User.class);
            Order order = orderService.getOrder(user.getUserId());
            order.setStatus(1);
            orderService.updateStatus(order);
            return "交易成功！";
        }
        return "交易失败!";

    }

    @RequestMapping(value = "/index")
    public String payCoin(){
        return "index.html";
    }
}
